﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

using EF.BLL.Base;
using EF.Model.Base;
using EF.Model;
using EF.Util;

public partial class Trans_Base_User : BasePage
{
    private UserService userBLL = new UserService();

    int userId = 0; //用户Id
    string lang = ""; //语言

    protected void Page_Load(object sender, EventArgs e)
    {
        CheckSession();

        userId = Convert.ToInt32(Session["uid"].ToString()); //用户Id
        lang = Session["lang"].ToString(); //语言

        Response.Clear();

        switch (Request["action"].ToString().ToLower())
        {
            case "list":
                GetList();
                break;
            case "history":
                GetHistory();
                break;
            case "restore":
                Restore();
                break;
            case "model":
                GetModel();
                break;
            case "add":
                Add(); //1,新建成功;2,新建失败,用户名已存在;0,新建失败,数据库异常.
                break;
            case "edit":
                Edit(); //1,编辑成功;0,编辑失败,数据库异常.
                break;
            case "logicdel": //1,逻辑删除成功;0,逻辑删除失败,数据库异常.
                LogicDel();
                break;
            case "export": //导出用户列表
                Export();
                break;
            default:
                break;
        }

        Response.End();
    }

    private void GetList()
    {
        try
        {
            int rowsCount; //总记录数

            int? pageSize = Request["limit"] == null ? Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"].ToString()) : Convert.ToInt32(Request["limit"].ToString());
            int? pageIndex = Request["start"] == null ? 1 : Convert.ToInt32(Request["start"].ToString()) / pageSize + 1;

            string sort = Request["sort"] == null ? "UpdateTime" : Request["sort"].ToString();
            string dir = Request["dir"] == null ? "DESC" : Request["dir"].ToString();

            string columns = "UserId,UserName,[Password],RealName,[Role],Sex,IdNumber,MobilePhone,Phone,SortIndex,CreateTime,UpdateTime"; //返回的列

            DataTable dt = userBLL.GetList(JsonHelp.ConvertJsonToParameterList(Request["search_params"].ToString()), lang, columns, pageIndex, pageSize, sort + " " + dir, out rowsCount);

            Response.Write("{success:true,rowsCount:" + rowsCount + ",rows:" + JsonHelp.WriteDataTable(dt)+"}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void GetHistory()
    {
        try
        {
            int rowsCount; //总记录数

            int? pageSize = Request["limit"] == null ? Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"].ToString()) : Convert.ToInt32(Request["limit"].ToString());
            int? pageIndex = Request["start"] == null ? 1 : Convert.ToInt32(Request["start"].ToString()) / pageSize + 1;

            string sort = Request["sort"] == null ? "UpdateTime" : Request["sort"].ToString();
            string dir = Request["dir"] == null ? "DESC" : Request["dir"].ToString();

            string columns = "UserId,UserName,[Password],RealName,[Role],Sex,IdNumber,MobilePhone,Phone,SortIndex,CreateTime,UpdateTime"; //返回的列

            DataTable dt = userBLL.GetHistory(lang, columns, pageIndex, pageSize, sort + " " + dir, out rowsCount);

            Response.Write("{success:true,rowsCount:" + rowsCount + ",rows:" + JsonHelp.WriteDataTable(dt) + "}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void Restore()
    {
        try
        {
            string selUserIds = Request["sel_user_id"].ToString();
            string msg = "";

            Response.Write("{success:true,result:" + userBLL.Restore(selUserIds, userId, lang, out msg) + ",msg:'" + msg + "'}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void GetModel()
    {
        try
        {
            int selUserId = Convert.ToInt32(Request["sel_user_id"].ToString());
            UserModel model = userBLL.GetModel(lang, selUserId);

            Response.Write("{success:true,rows:" + JsonHelp.Convert2Json(model) + "}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void Add() //1,新建成功;2,新建失败,用户名已存在;0,新建失败,数据库异常.
    {
        try
        {
            UserModel model = (UserModel)JsonHelp.Convert2Entity(Request["model"].ToString(), typeof(UserModel));
            model.CreateUser = userId;

            string msg;
            int result = userBLL.Add(model, lang, out msg);
            Response.Write("{success:true,result:" + result + ",msg:'" + msg + "'}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void Edit() //1,编辑成功;0,编辑失败,数据库异常.
    {
        try
        {
            UserModel model = (UserModel)JsonHelp.Convert2Entity(Request["model"].ToString(), typeof(UserModel));
            model.UpdateUser = userId;

            string msg;
            Response.Write("{success:true,result:" + userBLL.Edit(model, lang, out msg) + ",msg:'" + msg + "'}");
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void LogicDel() //1,逻辑删除成功;0,逻辑删除失败,数据库异常.
    {
        try
        {
            string selUserIds = Request["sel_user_id"].ToString();

            string msg;
            Response.Write("{success:true,result:" + userBLL.LogicDel(selUserIds, userId, lang, out msg) + ",msg:'" + msg + "'}");

        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }

    private void Export() //导出用户列表
    {
        try
        {
            string cols = Request["cols"].ToString();
            string colNames = Request["col_names"].ToString();

            string sort = Request["sort"] == null ? "UpdateTime" : Request["sort"].ToString();
            string dir = Request["dir"] == null ? "DESC" : Request["dir"].ToString();
            
            userBLL.Export(JsonHelp.ConvertJsonToParameterList(Request["search_params"].ToString()), cols, sort + " " + dir, colNames, lang);
        }
        catch (Exception ex)
        {
            Log.WriteLog(ex);
            Response.Write(GetErrorJson());
        }
    }
}
